﻿#include "chatdb.h"

ChatDB* ChatDB::m_pChatDB;
ChatDB::ChatDB(QObject *parent) : QObject(parent)
{
    m_pChatDB = nullptr;
    m_db = QSqlDatabase::addDatabase("QSQLITE","SysDB");
    m_db.setDatabaseName("ChatBase.db");
}

ChatDB *ChatDB::getInstance()
{
    if(m_pChatDB == nullptr)
        m_pChatDB = new ChatDB;
    return m_pChatDB;
}

bool ChatDB::initSysDB()
{
    m_db.open();
    closeDB();
    if(m_db.open())
    {
        QSqlQuery query(m_db);
        QString sql("create table if not exists 'userinfo'(id int primary key,nickname text,imgurl text)");
        if(!query.exec(sql))
        {
            CLog::getInstance()->writeLog("[ChatDB::initSysDB]=>Error: create userinfo table.\n");
            qDebug() << "[ChatDB::initSysDB]=>Error: create userinfo table." << m_db.lastError() << endl;
            return false;
        }
        closeDB();
    }
    else
    {
        CLog::getInstance()->writeLog("[ChatDB::initSysDB]=>Error: database not exist.\n");
        qDebug() << "[ChatDB::initSysDB]=>Error: database not exist.\n";
        return false;
    }
    return true;
}

bool ChatDB::initUserDB(const QString &path)
{
    m_userDB = QSqlDatabase::addDatabase("QSQLITE","UserDB");
    m_userDB.setDatabaseName(path);
    m_userDB.open();
    closeDB();
    if(m_userDB.open())
    {
        QSqlQuery query(m_userDB);
        QString sql("create table userinfo(id int primary key,nickname text,imgurl text,sex text,age tinyint,address text,phone text,signatrue text)");
        if(!query.exec(sql))
        {
            CLog::getInstance()->writeLog("[ChatDB::initUserDB]=>Error: create userinfo table.\n");
            qDebug() << "[ChatDB::initUserDB]=>Error: create userinfo table." << m_db.lastError() << endl;
            return false;
        }
        QString sql2("create table friend(id int primary key,nickname text,imgurl text,sex text,age tinyint,address text,phone text,signatrue text)");
        if(!query.exec(sql2))
        {
            CLog::getInstance()->writeLog("[ChatDB::initDB]=>Error: create friend table.\n");
            qDebug() << "[ChatDB::initDB]=>Error: create friend table." << m_db.lastError() << endl;
            return false;
        }
        QString sql3("create table groupinfo(id int,name text,imgurl text)");
        if(!query.exec(sql3))
        {
            CLog::getInstance()->writeLog("[ChatDB::initDB]=>Error: create groupinfo table.\n");
            qDebug() << "[ChatDB::initDB]=>Error: create groupinfo table." << m_db.lastError() << endl;
            return false;
        }
        QString sql4("create table groupinfo2(groupid int,userid int)");
        if(!query.exec(sql4))
        {
            CLog::getInstance()->writeLog("[ChatDB::initDB]=>Error: create groupinfo2 table.\n");
            qDebug() << "[ChatDB::initDB]=>Error: create groupinfo2 table." << m_db.lastError() << endl;
            return false;
        }
        closeDB();
    }
    else
    {
        CLog::getInstance()->writeLog("[ChatDB::initUserDB]=>Error: create userinfo table.\n");
        qDebug() << "[ChatDB::initUserDB]=>Error: create database fail." << m_db.lastError() << endl;
        return false;
    }
    return true;
}

bool ChatDB::openSysDB()
{
    if(!m_db.open())
    {
        CLog::getInstance()->writeLog("[ChatDB::openSysDB]=>Error: Failed to connect database.\n");
        qDebug() << "[ChatDB::openSysDB]=>Error: Failed to connect database." << m_db.lastError() << endl;
        return false;
    }
    return true;
}

bool ChatDB::openUserDB()
{
    if(!m_userDB.open())
    {
        CLog::getInstance()->writeLog("[ChatDB::openUserDB]=>Error: Failed to connect database.\n");
        qDebug() << "[ChatDB::openUserDB]=>Error: Failed to connect database." << m_db.lastError() << endl;
        return false;
    }
    return true;
}

void ChatDB::closeDB()
{
    if(m_db.isOpen())
        m_db.close();
    if(m_userDB.isOpen())
        m_userDB.close();
}

void ChatDB::addUser(const QString& uid,const QString& nickname)
{
    QString sql = QString("insert into userinfo values(%1,'%2','res/head/defualtHead.png')").arg(uid).arg(nickname);
    openSysDB();
    QSqlQuery query(sql,m_db);
    query.exec();
    closeDB();
}

void ChatDB::addUser(const QString &uid, const QString &nickname, const QString headUrl)
{
    QString sql = QString("insert into userinfo values(%1,'%2','%3')").arg(uid).arg(nickname).arg(headUrl);
    openSysDB();
    QSqlQuery query(sql,m_db);
    query.exec();
    closeDB();
}

QString ChatDB::getImgUrl(const QString &id)
{
    QString imgurl = "";
    if(!openSysDB())
        return "";
    QString sql = QString("select imgurl from userinfo where id = %1").arg(id);
    QSqlQuery query(sql,m_db);
    if(!query.exec())
    {
        CLog::getInstance()->writeLog("[ChatDB::getImgUrl]=>Error.\n");
        qDebug() << "[ChatDB::getImgUrl]=>Error." << m_db.lastError() << endl;
        return imgurl;
    }
    if(query.next())
    {
        imgurl = query.value(0).toString();
    }
    closeDB();
    return imgurl;
}

QString ChatDB::getNickName(const QString &id)
{
    QString nickname = "";
    if(!openSysDB())
        return "";
    QString sql = QString("select nickname from userinfo where id = %1").arg(id);
    QSqlQuery query(sql,m_db);
    if(!query.exec())
    {
        CLog::getInstance()->writeLog("[ChatDB::getNickName]=>Error.\n");
        qDebug() << "[ChatDB::getNickName]=>Error." << m_db.lastError() << endl;
        return nickname;
    }
    if(query.next())
    {
        nickname = query.value(0).toString();
    }
    closeDB();
    return nickname;
}

QString ChatDB::getSignatrue(const QString &id)
{
    QString signatrue = "";
    if(!openUserDB())
        return "";
    QString sql = QString("select signatrue from userinfo where id = %1").arg(id);
    QSqlQuery query(sql,m_userDB);
    if(!query.exec())
    {
        CLog::getInstance()->writeLog("[ChatDB::getSignatrue]=>Error.\n");
        qDebug() << "[ChatDB::getSignatrue]=>Error." << m_userDB.lastError() << endl;
        return signatrue;
    }
    if(query.next())
    {
        signatrue = query.value(0).toString();
    }
    closeDB();
    return signatrue;
}

void ChatDB::deleteUserInfo(const QString &id)
{
    if(!openSysDB())
        return;
    QString sql = QString("delete from userinfo where id = %1").arg(id);
    QSqlQuery query(sql,m_db);
    query.exec();
    closeDB();
}

void ChatDB::updateUserInfo(const Json::Value &root, int type)
{
    if(!openUserDB())
        return;
    if(type == 0)//更新用户自己的个人信息
    {
        QString id = root["ID"].asCString();
        QString nickname = root["NickName"].asCString();
        QString sex = root["Sex"].asCString();
        QString age = root["Age"].asCString();
        QString address = root["Address"].asCString();
        QString phone = root["Phone"].asCString();
        QString headUrl = root["HeadUrl"].asCString();
        QString perSig = root["PerSig"].asCString();
        //id int primary key,nickname text,imgurl text,sex text,age tinyint,address text,phone text,signatrue text
        QString sql = QString("insert into userinfo values(%1,'%2','%3','%4',%5,'%6','%7','%8')").arg(id).arg(nickname).arg(headUrl).arg(sex).arg(age).arg(address).arg(phone).arg(perSig);
        QSqlQuery query(sql,m_userDB);
        query.exec();
    }
//    else if(type == 1)//更新好友信息
//    {
//        for(int i = 0;i < root.size(); i++)
//        {
//            QString id = root[i]["ID"].asCString();
//            QString nickname = root[i]["NickName"].asCString();
//            QString sex = root[i]["Sex"].asCString();
//            QString age = root[i]["Age"].asCString();
//            QString address = root[i]["Address"].asCString();
//            QString phone = root[i]["Phone"].asCString();
//            QString headUrl = root[i]["HeadUrl"].asCString();
//            QString perSig = root[i]["PerSig"].asCString();
//            //id int primary key,nickname text,imgurl text,sex text,age tinyint,address text,phone text,signatrue text
//            QString sql = QString("insert into friend values(%1,'%2','%3','%4',%5,'%6','%7','%8')").arg(id).arg(nickname).arg(headUrl).arg(sex).arg(age).arg(address).arg(phone).arg(perSig);
//            QSqlQuery query(sql,m_userDB);
//            query.exec();
//        }
//    }
    closeDB();
}
